// 轮播图数据存储服务

class CarouselStore {
  constructor() {
    // 初始化轮播图数据
    this.carouselImages = JSON.parse(localStorage.getItem('carouselImages')) || [];
    this.listeners = [];
    this.isLoading = false;
  }

  // 添加数据变化监听器
  addListener(listener) {
    if (!this.listeners.includes(listener)) {
      this.listeners.push(listener);
    }
  }

  // 移除数据变化监听器
  removeListener(listener) {
    this.listeners = this.listeners.filter(l => l !== listener);
  }

  // 通知所有监听器数据已更新
  notifyListeners() {
    this.listeners.forEach(listener => {
      try {
        listener();
      } catch (error) {
        console.error('Error in listener:', error);
      }
    });
  }

  // 保存数据到本地存储
  saveToLocalStorage() {
    localStorage.setItem('carouselImages', JSON.stringify(this.carouselImages));
    this.notifyListeners();
  }

  // 获取所有轮播图
  getAllCarouselImages() {
    // 按创建时间排序，最新的在前面
    return [...this.carouselImages].sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
  }

  // 根据ID获取轮播图
  getCarouselImageById(id) {
    return this.carouselImages.find(image => image.id === id);
  }

  // 添加新的轮播图
  addCarouselImage(imageData) {
    try {
      const newImage = {
        id: Date.now().toString(),
        ...imageData,
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      };
      this.carouselImages.push(newImage);
      this.saveToLocalStorage();
      return newImage;
    } catch (error) {
      console.error('Failed to add carousel image:', error);
      return null;
    }
  }

  // 更新轮播图
  updateCarouselImage(id, imageData) {
    try {
      const index = this.carouselImages.findIndex(image => image.id === id);
      if (index !== -1) {
        this.carouselImages[index] = {
          ...this.carouselImages[index],
          ...imageData,
          updatedAt: new Date().toISOString()
        };
        this.saveToLocalStorage();
        return this.carouselImages[index];
      }
      return null;
    } catch (error) {
      console.error('Failed to update carousel image:', error);
      return null;
    }
  }

  // 删除轮播图
  deleteCarouselImage(id) {
    try {
      const initialLength = this.carouselImages.length;
      this.carouselImages = this.carouselImages.filter(image => image.id !== id);
      
      if (this.carouselImages.length !== initialLength) {
        this.saveToLocalStorage();
        return true;
      }
      return false;
    } catch (error) {
      console.error('Failed to delete carousel image:', error);
      return false;
    }
  }

  // 上传图片文件
  async uploadImage(file) {
    try {
      // 在实际项目中，这里应该调用后端API上传图片
      // 这里使用Base64编码模拟图片上传
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
          resolve(e.target.result);
        };
        reader.onerror = () => {
          reject(new Error('图片上传失败'));
        };
        reader.readAsDataURL(file);
      });
    } catch (error) {
      console.error('Failed to upload image:', error);
      throw error;
    }
  }

  // 更新轮播图顺序
  updateCarouselOrder(ids) {
    try {
      const orderedImages = [];
      ids.forEach(id => {
        const image = this.carouselImages.find(img => img.id === id);
        if (image) {
          orderedImages.push(image);
        }
      });
      // 添加剩余未指定顺序的图片
      this.carouselImages.forEach(image => {
        if (!ids.includes(image.id)) {
          orderedImages.push(image);
        }
      });
      this.carouselImages = orderedImages;
      this.saveToLocalStorage();
      return true;
    } catch (error) {
      console.error('Failed to update carousel order:', error);
      return false;
    }
  }
}

// 导出单例
const store = new CarouselStore();
export default store;